const {getCommentList, getCommentOne, delComment, updateComment, createComment} = require('../service/comment')
const {SuccessModel, ErrorModel} = require('../model/ResModel')
const {addRoleFailInfo} = require('../model/ErrorInfo')
const {flatData} = require('../utils/flatData')

const getComment = async ({pageIndex = 0, pageSize = 10}) => {
  const result = await getCommentList({pageIndex, pageSize})
  result.data = flatData(result.data)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const getCommentById = async (id) => {
  let result = await getCommentOne(+id)
  result.house = flatData(result.house)
  result.replies = flatData(result.replies)
  result = flatData(result)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const postComment = async (ctx, {title, content, imgs, houseId}) => {
  const result = await createComment({
    title,
    content,
    imgs,
    uid: ctx.session.user.user.id,
    houseId
  })
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const patchComment = async ({title, content, imgs, id}) => {
  const result = await updateComment({title, content, imgs, id})
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const deleteComment = async (id) => {
  const result = await delComment(id)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

module.exports = {
  getComment,
  getCommentById,
  postComment,
  patchComment,
  deleteComment
}
